<template>
  <!-- 采购订单-->
  <div class="page">
    <!-- 条件筛选 -->
    <div class="page_filter">
      <el-input v-model="form.queryString" clearable placeholder="单号/说明">
        <template slot="prepend">查询条件</template>
      </el-input>
      <el-select v-model="form.storeStatus" style="width: 150px;" clearable placeholder="入库状态">
        <el-option
          v-for="item in EnumInOrderStatusSelectList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
      <el-select v-model="form.volumeStatus" style="width: 150px;" clearable placeholder="付款状态">
        <el-option
          v-for="item in EnumVolumeOutStatusList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
      <el-select v-model="form.companyId" clearable filterable placeholder="请选择供应商公司">
        <el-option
          v-for="item in companyList"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
      <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
    </div>
    <div class="page_main">
      <el-button icon="iconfont iconcangpeitubiao_chuangjianrukudan icon_size_15" class="common_btn-small"
                 @click="addOrder()">填写采购单
      </el-button>
      <!-- table -->
      <div class="common_btnBox">
        <i class="iconfont iconzongshu icon-size"></i>
        总数：{{form.total}}
      </div>
      <el-table :data="tableList" border>
        <el-table-column label="序号" fixed width="80">
          <template slot-scope="scope">
            {{getIndex(scope.$index)}}
          </template>
        </el-table-column>
        <el-table-column prop="orderNo" label="单号" width="170"></el-table-column>
        <el-table-column prop="orderType" show-overflow-tooltip label="入库状态" width="110">
          <template slot-scope="scope">
            <el-tag :style="scope.row.storeStatus| gradeInOrderStatusColor" style="color: white" size="mini">
              {{scope.row.storeStatusName}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="volumeStatus" show-overflow-tooltip label="付款状态" width="110">
          <template slot-scope="scope">
            <el-tag :style="scope.row.volumeStatus| gradeInOrderStatusColor" style="color: white" size="mini">
              {{scope.row.volumeStatusName}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="salesVolume" label="采购总额" show-overflow-tooltip min-width="100"></el-table-column>
        <el-table-column prop="salesVolume2" label="已付账款" show-overflow-tooltip min-width="100"></el-table-column>
        <el-table-column prop="salesVolume3" label="待付账款" show-overflow-tooltip min-width="100"></el-table-column>
        <el-table-column prop="explanation" label="备注" show-overflow-tooltip min-width="120"></el-table-column>
        <el-table-column prop="companyName" label="供应商" show-overflow-tooltip min-width="120"></el-table-column>
        <el-table-column prop="userName" label="采购人员" show-overflow-tooltip min-width="120"></el-table-column>
        <el-table-column prop="toTime" label="采购日期" width="120">
          <template slot-scope="scope">{{scope.row.toTime | formatTimer2}}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template slot-scope="scope">
            <button class="btn_edit" @click="handleEdit(scope.row,true)">查看详情</button>
            <button class="btn_add" @click="handleEdit(scope.row,false)" v-if="scope.row.storeStatus === 1">编辑</button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
                     :page-size="form.pageSize"    :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
                     layout="sizes, prev, pager, next" :total="form.total">
      </el-pagination>
      <!--  采购单填写-->
      <el-drawer
        title="采购订单"
        :visible.sync="isShowAddDialog"
        direction="rtl"
        custom-class="demo-drawer"
        ref="drawer"
        size="60%">
        <div class="demo-drawer__content">
          <div class="goods_compose_class">
            <el-form label-position="right" ref="order" label-suffix="：" :rules="rule" :model="order"
                     label-width="90px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item prop="userName" label="采购人员">
                    <el-input style="width: 50%;" disabled v-model="order.userName"></el-input>
                  </el-form-item>
                  <el-form-item prop="toTime" label="采购日期" label-width="100px">
                    <el-date-picker
                      :disabled="isLook"
                      v-model="order.toTime"
                      type="date"
                      style="width: 50%;"
                      placeholder="选择采购日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item prop="companyId" label="供应商">
                    <el-select v-model="order.companyId" :disabled="isLook" style="width: 90%" clearable filterable
                               placeholder="请选择供应商">
                      <el-option
                        :disabled="isLook"
                        v-for="item in companyList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                    <i class="el-icon-refresh icon-size" style="cursor: pointer;"
                       @click="removeAllCompanyStorage"></i>
                  </el-form-item>
                  <el-form-item prop="explanation" label="备注">
                    <el-input :disabled="isLook" v-model="order.explanation" style="width: 90%" type="textarea"
                              :autosize="{ minRows: 3, maxRows: 5}"
                              placeholder="请输入采购补充说明"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <!--相关文件-->
                  <el-form-item label="相关文件" prop="fileList">
                    <template v-if="isLook">
                      <el-alert
                        :closable="false" title="可点击下载" type="info" show-icon>
                      </el-alert>
                      <a v-for="file in order.fileList" :key="file.url" style="background: #1990FE; color: white"
                         :href="constUrl + file.url"
                         :download="file.name">
                        <el-button icon="el-icon-document" style="background:#1990FE;color: white" size="mini">
                          {{file.name}}
                        </el-button>
                      </a>
                    </template>
                    <template v-else>
                      <el-alert
                        :closable="false" title="建议上传采购单对应的合同文件！" type="info" show-icon>
                      </el-alert>
                      <upload-file :limit="3" v-model="order.fileList" ref="uploadClear"></upload-file>
                    </template>
                  </el-form-item>
                  <!--相关图片-->
                  <el-form-item label="相关图片" prop="picList">
                    <template v-if="isLook">
                      <el-alert
                        :closable="false" title="可点击查看大图" type="info" show-icon>
                      </el-alert>
                      <el-image
                        style="width: 100px; height: 100px;cursor: pointer" :key="img" v-for="img in order.picList"
                        :src="constUrl + img" @click="previewImg(constUrl + img)"
                        fit="fill"></el-image>
                    </template>
                    <template v-else>
                      <el-alert
                        :closable="false" title="建议上传采购相关的图片证明！" type="info" show-icon>
                      </el-alert>
                      <upload-img v-model="order.picList" :limit="3" :size-limit="3" ref="uploadPic"></upload-img>
                    </template>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-button icon="el-icon-plus" type="primary" @click="addGoodsCompose" :disabled="isLook ">添加采购项
              </el-button>
              <el-table height="35vh" border :data="order.formationListTemp" class="m-t-24">
                <el-table-column label="名称" min-width="260px">
                  <template slot-scope="scope">
                    <el-select size="small" value-key="id" style="width: 90%" :disabled="isLook"
                               v-model="scope.row.formation" filterable
                               placeholder="请选择货品"
                               clearable>
                      <el-option
                        v-for="item in goodsSelectList"
                        :key="item.id"
                        :label="item.name"
                        :value="item"
                        :disabled="disableGoodsSelect.indexOf(item.id) !== -1">
                      </el-option>
                    </el-select>
                    <i class="el-icon-refresh icon-size" style="cursor: pointer;" @click="removeAllGoodsStorage"></i>
                  </template>
                </el-table-column>
                <el-table-column label="类型" min-width="100px">
                  <template slot-scope="scope">
                    {{scope.row.formation?scope.row.formation.goodsEnumName:'---'}}
                  </template>
                </el-table-column>
                <el-table-column label="分类" min-width="100px">
                  <template slot-scope="scope">
                    {{scope.row.formation?scope.row.formation.goodsTypeName:'---'}}
                  </template>
                </el-table-column>
                <el-table-column label="规格" min-width="100px">
                  <template slot-scope="scope">
                    {{scope.row.formation?scope.row.formation.specifications:'---'}}
                  </template>
                </el-table-column>
                <el-table-column label="采购价" min-width="150px">
                  <template slot-scope="scope">
                    <el-input size="small" v-if="scope.row.formation"
                                     v-model="scope.row.formation.costVolume"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="采购数量" min-width="150px">
                  <template slot-scope="scope">
                    <el-input-number size="small" v-if="scope.row.formation"
                                     :disabled="isLook"
                                     v-model="scope.row.formation.formationNumber"
                                     :min="1"></el-input-number>
                    <span v-else>---</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="90" v-if="!isLook">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      class="btn_delete"
                      @click="handleDeleteImg(scope.$index)">删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="text-align: right">
                <el-form-item prop="salesVolume" label-width="0px">
                  <el-input disabled style="width: 250px" v-model="salesVolume">
                    <template slot="prepend">总金额</template>
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </div>
        <div class="demo-drawer__footer">
          <el-button @click="isShowAddDialog=false" type="info">取 消</el-button>
          <el-button type="primary" class="common_btn-defalut" @click="validateAddForm">确 定</el-button>
        </div>
      </el-drawer>
    </div>
    <x-loading v-show="isLoading"></x-loading>
    <picture-viewer ref="imageViewer"></picture-viewer>
  </div>
</template>
<script>
import {
  getPurchaseOrderList,
  addPurchaseOrder,
  updatePurchaseOrder,
} from '@/services/ERP/order'
import UploadFile from '@/components/upload-file'
import ItemMixins from "../item.mixins";
import UploadImg from '@/components/upload-img'
import XLoading from '@/components/animation/x-loading.vue'
import PictureViewer from '@/components/picture-viewer'
import Enums from '@/utils/enums'

// form表单校验规则
export default {
  components: {XLoading, UploadFile, UploadImg, PictureViewer},
  mixins: [ItemMixins,Enums],
  data() {
    return {
      form: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      rule: {
        toTime: {required: true, message: '请选择采购日期'},
        companyId: {required: true, message: '请选择供应商'},
      },
      order: {
        goodsList: [],
        formationListTemp: [],
        fileList: [],
        picList: [],
        parentOrderId: ''
      },
      orderConfirm: {},
      tableList: [],
      orderList: [],
      EnumInOrderStatusList: [],
      EnumVolumeOutStatusList: [],
      isShowAddDialog: false,
      isLoading: false,
    }
  },
  computed: {
    goodsSelectList() {
      return JSON.parse(JSON.stringify(this.allGoodsSelectList))
    },
    salesVolume() {
      let money = 0;
      this.order.formationListTemp.map(x => {
        if (x.formation) {
          money += x.formation.costVolume * x.formation.formationNumber
        }
      })
      return money
    },
    companyList() {
      return this.allCompanyList.filter(x => x.type === 1)
    },
    EnumInOrderStatusSelectList() {
      return this.EnumInOrderStatusList.filter(x => x.code !== 4)
    },
    isLook() {
      return this.order.isLook
    },
    //已经选择了的货品不能再选
    disableGoodsSelect() {
      let list = []
      this.order.formationListTemp.map(x => {
        if (x.formation) {
          list.push(x.formation.id)
        }
      })
      return list
    },
  },
  methods: {
    // 查看大图
    previewImg(url) {
      let list = [url]
      this.$refs.imageViewer.showViewer(list, 0)
    },
    //删除一个货品
    handleDeleteImg(index) {
      this.order.formationListTemp.splice(index, 1);
    },
    //添加一个货品
    addGoodsCompose() {
      this.order.formationListTemp.push({})
    },
    // 表单提交
    validateAddForm() {
      //如果是查看，且不是出库确认直接关闭弹窗
      if (this.isLook) {
        this.isShowAddDialog = false
        return
      }
      this.$refs.order.validate((valid) => {
        if (valid) {
          this.submitOrder()
        }
      })
    },
    async submitOrder() {
      let goodsList = []
      //处理货品组成数据
      this.order.formationListTemp.map(x => {
        goodsList.push({
          goodsId: x.formation.id,
          saleVolume: x.formation.costVolume,
          goodsNumber: x.formation.formationNumber,
        })
      })
      this.order.salesVolume = this.salesVolume
      this.order.goodsList = goodsList
      let form = this.order
      let action = this.order.id ? updatePurchaseOrder : addPurchaseOrder
      let res = await action(form)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: this.order.id ? '更新成功' : '添加成功！'
        })
        this.isShowAddDialog = false
        this.order.formationListTemp = []
        this.queryList()
      }
    },
    // 获取当前的序号
    getIndex(index) {
      let param = (this.form.page - 1) * this.form.pageSize + index + 1
      return param
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.form.pageSize = val
      this.queryList()
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.form.page = val
      this.queryList()
    },
    async queryList() {
      this.isLoading = true
      let res = await getPurchaseOrderList(this.form)
      this.tableList = res.data?.records || []
      this.form.page = Number(res.data?.current)
      this.form.total = Number(res.data?.total)
      this.isLoading = false
    },
    addOrder() {
      this.isShowAddDialog = true
      this.order = {
        formationListTemp: [],
        fileList: [],
        picList: [],
        userName: this.user.userName
      }
      this.$nextTick(() => {
        this.$refs.order.clearValidate()
      })
    },
    handleEdit(row, isLook) {
      this.isShowAddDialog = true
      this.order = JSON.parse(JSON.stringify(row))
      let formationListTemp = []
      //处理货品组成数据，用于回显
      this.order.goodsList.map(x => {
        this.goodsSelectList.map(y => {
          if (x.goodsId === y.id) {
            let temp = JSON.parse(JSON.stringify(y))
            temp.formationNumber = x.goodsNumber
            temp.costVolume = x.saleVolume
            formationListTemp.push({formation: temp})
          }
        })
      })
      this.order.formationListTemp = formationListTemp
      this.order.isLook = isLook
      this.$nextTick(() => {
        this.$refs.order.clearValidate()
      })
    },
  },
  mounted() {
    this.queryDictList(['EnumInOrderStatus', 'EnumVolumeOutStatus'], ['EnumInOrderStatusList', 'EnumVolumeOutStatusList'])
    this.queryList()
  },
  activated() {
    this.getAllGoodsSelectList()
    this.getAllCompanyList()
  }

}
</script>

<style lang="less" scoped>
  .goods_compose_class {
    padding: 20px;

    /deep/ .el-table th {
      padding: 5px 0;
    }

    /deep/ .el-table td {
      padding: 5px 0;

      .el-input-number {
        width: 120px;
      }

      .el-input-number__decrease, .el-input-number__increase {
        width: 30px;
      }
    }
  }


  .el-divider__text {
    font-size: 20px;
  }

  /deep/ .el-divider--horizontal {
    display: block;
    height: 1px;
    width: 100%;
    margin: 30px 0;
  }

  /deep/ .el-input-group__prepend {
    border-right: 0;
    background: #2196f3;
    color: white;
  }
</style>
